import { useCurrencyStore } from '~/stores';
import { jsBridge } from '~/utils/defines';
import { getGameInfo } from './helpers';

export default defineRouteGuard({
  setup(router) {
    const selfGamePage = () => import('./self/index.vue');
    const aloneGamePage = () => import('./alone/index.vue');
    const thirdPartyGamePage = () => import('./third-party/index.vue');

    router.beforeEach(async (to) => {
      // 只对 play 路由进行拦截
      if (to.name !== RN.PLAY) {
        return true;
      }

      const isTest = import.meta.env.DEV && to.params.gameCode === 'dev' && typeof to.query.url === 'string';
      if (isTest)
        return true;

      const gameCode = String(to.params.gameCode);
      const gameInfo = await getGameInfo(gameCode);

      if (!gameInfo)
        return { name: RN.INDEX };

      if (gameInfo.status === 1) {
        const isAloneGame = gameInfo.self && gameInfo.open_method === 1;

        if (isAloneGame && !hasToken()) {
          antdMessage.warning($t('gy0QaFjSyErjUIcpWzxo0'));
          setTimeout(() => globalPopups.sign.open(), 500);
          return { name: RN.INDEX };
        }

        if (to.matched[1]?.components) {
          // 根据游戏类型切换页面
          to.matched[1].components.default = gameInfo.self
            ? (isAloneGame ? aloneGamePage : selfGamePage)
            : thirdPartyGamePage;
        }

        jsBridge.post('enterGame', { gameCode });

        return true;
      }

      if (gameInfo?.status === 0) {
        antdMessage.warning($t('f8gcyI8MeDcdRawzbgNWi'));
        return false;
      }

      return false;
    });

    router.afterEach(async (to, from) => {
      // 当进入或退出游戏页面时刷新余额
      if (to.name === RN.PLAY || from.name === RN.PLAY) {
        try {
          useCurrencyStore().refetch();
        }
        catch {}
      }
    });
  },
});
